<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2014/10/9
 * Time: 10:50
 * 问题题目表
 */
class QuestionSubject extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
		return parent::model($className);
    }
	
    public function tableName()
    {
        return 'question_subject';
    }
	
	private static $tableFields = array(
		'question_id',
		'subject_type',
		'question_num',
		'is_basic',
		'classify_id',
		'question_type',
		'question_type_sub',
		'title',
		'content',
		'standard_score',
		'extend',
		'reorder',
		'create_time',
		'update_time',
		'status',
	);


	//题型定义
	public static $question_type = array(
		1 => array(
			'title' => '填空题',
			'title_en' => 'fill_blanks'
		),
		2 => array(
			'title' => '选择题',
			'title_en' => 'select',
			'cate' => array(
				3 => '单选',
				4 => '多选',
//				5 => '下拉'
			)
		),
		6 => array(
			'title' => '得分题',
			'title_en' => 'score',
			'cate' => array(
				7 => '得分',
//				8 => '加分',
//				9 => '扣分'
			)
		),
		10 => array(
			'title' => '描述题',
			'title_en' => 'description'
		)
	);
	
	/**
	 * 得分题显示项设置
	 */
	public static $score_display_item = array(
		1 => '被扣分人员（选项内容）'
	);
	
	/**
	 * 填空题文本类型
	 */
	public static $fill_text_type = array(
		1 => '单行文本',
		2 => '文本域'
	);
	
	/**
	 * 
	 */
	public static $fill_data_type = array(
		10 => '不限',
		20 => '数字',
		30 => '日期',
		31 => '日期精确到分'
	);
        //得到基本信息
        public function getBasic($question_id)
        {
            return $this->findAll('question_id='.$question_id.' and is_basic=1');
        }
	/**
	 * 获取题型
	 * @param type $typeId
	 * @return boolean
	 */
	public static function getQuestionType($typeId=null){
		$types = self::$question_type;
		return $typeId ? $types[$typeId] : $types;
	}
	
	/**
	 * 检查题型是否存在于定义的题型中，存在返回key和关联的上级，下级题型，不存在，返回false
	 * @param string $type
	 * @return boolean
	 */
	public static function checkTypeIn($type){
		if(!$type){
			return false;
		}
		$return = array();
		foreach (self::$question_type as $key => $data) {
			if($type == $data['title']){
				$return[$key]['title'] = $data['title'];
				break;
			}
			if(isset($data['cate'])){
				foreach ($data['cate'] as $i => $v) {
					if($type == $v){
						$return[$i] = array(
							'title' => $v,
							'parent_key' => $key,
							'parent_title' => $data['title']
						);
						break;
					}
				}
			}
		}
		return $return;
	}
	
	/**
	 * 删除问卷的所有内容
         * 同时更新网点问卷的得分为0
	 * @param type $questionId
	 * @return boolean
	 */
	public function deleteQuestion($questionId){
		if(!$questionId){
			return false;
		}
		$delClassifyStatus = QuestionSubjectClassify::model()->deleteAll('question_id=:question_id', array(':question_id'=>$questionId));
		$delSubjectStatus = $this->deleteAll('question_id=:question_id', array(':question_id'=>$questionId));
                NetworkQuestion::model()->updateAll(array('score' => '0','op_node_id' =>'0','node_id' => '0','audit'=>'0','status' => 1),'question_id=:question_id',array(':question_id'=>$questionId));
		return $delClassifyStatus && $delSubjectStatus;
	}

	

	/**
	 * 添加问卷分类
	 * @param type $questionId
	 * @param type $classifys
	 * @return type
	 */
	public function addQuestionClassify($questionId, array $classifys){
		if (!$questionId) {
			return false;
		}
		
		$classifyIds = array();
		
		//分级插入
		foreach ($classifys as $key => $value) {
			$questionSubjectClassify = new QuestionSubjectClassify();
			if ($value['classify_type'] != QuestionSubjectClassify::QUESTION_NORM_ONE) {
				$criteria =new CDbCriteria();
				$criteria->addCondition('classify_name="' . $value['parent_name'] . '"');
				$criteria->order = "classify_id DESC";
				$criteria->limit = 1;
				$classifyData = $questionSubjectClassify->find($criteria);
				unset($value['parent_name']);
				if ($classifyData) {
					$value['parent_id'] = $classifyData->classify_id;
				}
			}
			
			$questionSubjectClassify->question_id = $questionId;
			$questionSubjectClassify->classify_name = $value['classify_name'];
			$questionSubjectClassify->classify_type = $value['classify_type'];
			$questionSubjectClassify->parent_id = $value['parent_id'];
			$questionSubjectClassify->create_time = $value['create_time'];
			$questionSubjectClassify->status = $value['status'];			
			$status = $questionSubjectClassify->save();
			$classifyIds[$key] = $status ? $questionSubjectClassify->attributes['classify_id'] : 0;
			unset($questionSubjectClassify);
		}
		
		return $classifyIds;
	}
	
	/**
	 * 添加问题选项
	 * @param type $questionId
	 * @param type $questionSubjectId
	 * @param type $options
	 * @return boolean
	 */
	public function addQuestionOption($questionId, $questionSubjectId, $options){
		if(!$questionId || !$questionSubjectId){
			return false;
		}
		
		//添加之前先删除
		QuestionOption::model()->deleteAll('question_id=:question_id and subject_id=:subject_id', array(
			':question_id' => $questionId,
			':subject_id' => $questionSubjectId
		));
		
		$questionOption = new QuestionOption();
		$questionOption->question_id = $questionId;
		$questionOption->subject_id = $questionSubjectId;
		$questionOption->content = json_encode($options);
		return $questionOption->save();
	}
	
	/**
	 * 添加问卷题目
	 * @param type $questionId
	 * @param array $insertData
	 * @return boolean
	 */
	public function addQuestionSubject($questionId, array $insertData){
		if(empty($insertData)){
			return false;
		}
		$insertStatus = true;
		foreach ($insertData as $index => $value) {
			$pk = $value['subject_id'] ? $value['subject_id'] : 0;
			unset($value['subject_id']);
			$insertOne = $this->questionEachInsert($value);
			$subjectId = 0;
			
			if ($insertOne['subject']) {
				$questionSubject = new self();
				// 更新
				if ($pk) {
					$questionSubject->updateByPk($pk, $insertOne['subject']);
					$subjectId = $pk;
					
				}else{
					// 添加
					foreach ($insertOne['subject'] as $i => $v) {
						$questionSubject->$i = $v;
						$questionSubject->create_time = time();
					}
					$status = $questionSubject->save();
					$subjectId = ($insertStatus && $status) ? $questionSubject->attributes['subject_id'] : 0;
				}
			}
			
			if ($questionId && $subjectId && $insertOne['option']) {
				$optionStatus = $this->addQuestionOption($questionId, $subjectId, $insertOne['option']);
				$insertStatus &= $optionStatus;		
			}
		}
		
		return $insertStatus;
	}
	
	/**
	 * 区分出不同题型的插入数据
	 * @param type $insertData
	 */
	public function questionEachInsert($insertData){
		$eachInsert = array();
		// option(得分，选择)
		if (in_array($insertData['question_type'], array(2,6))) {
			$eachInsert['option'] = $insertData['option'];
			unset($insertData['option']);
		}
		
		// extend
		$tableFields = self::$tableFields;
		$diff = array_diff(array_keys($insertData), $tableFields);
		if($diff){
			foreach ($diff as $value) {
				if ($insertData['extend']) {
					$insertData['extend'] = array_merge($insertData['extend'], array($value=>$insertData[$value]));
				}else{
					$insertData['extend'][$value] = $insertData[$value];
				}
				unset($insertData[$value]);
			}
			$insertData['extend'] = json_encode($insertData['extend']);
		}
		$eachInsert['subject'] = $insertData;
		return $eachInsert;
	}


	/**
     * 根据问卷获得详细题目
     * @param $question_id 问卷ID
     * @param 是否已归类组的形式返回
     */
    public function getListByBase($question_id, $is_classify=false){
        $criteria = new CDbCriteria();
		$criteria->addColumnCondition(array('question_id' => $question_id));
        $criteria->addColumnCondition(array('status' => 1));
        $criteria->order = 'reorder desc';
		$data = $this->findAll($criteria);

        if ($data){
            return $this->formatSubject($data, $is_classify);
        }
        return $data;
    }
	
	/**
	 * 格式化题目数据
	 */
	public function formatSubject($data, $is_classify=false) {
		if (!$data) {
			return array();
		}
		$classify_result = array();
		$result = array();
		$option = new QuestionOption();
		foreach ($data as $key => $val) {
			$val['extend'] = json_decode($val['extend'], true);
			$classify_id = $val['classify_id'];
			$classify_result[$classify_id][$val['question_num']] = $val;

			$result[$val['question_num']] = $val;
			if ($val['question_type'] == 2 || $val['question_type'] == 6) {
				$option_list = $option->getBySubject($val['question_id'], $val['subject_id']);
				$option_list_array = json_decode(array_pop($option_list), true);
				$result[$val['question_num']]['option'] = $option_list_array;
				$classify_result[$classify_id][$val['question_num']]['option'] = $option_list_array;
			}
		}
		if ($data[0]['question_id'] == 875 || $data[0]['question_id'] == 870) {
            //print_r($result);exit;
        }

		return $is_classify ? $classify_result : $result;
		
	}
	
    /**
     * 获取分类分组数据
     */
    public function getByGroupClassify($question_id){
        $data = $this->findAll('question_id='.$question_id);
        if ($data) {
            $result = array();
            foreach ($data as $key => $val) {
                $classify_id = $val['classify_id'];
                $result[$classify_id][$key] = $val;
            }
            return $result;
        }
        return $data;
    }
}